﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TemplatesPrint.DBHelper;
using TemplatesPrint.DTO;
using TemplatesPrint.EntityHandle;
using TemplatesPrint.Entitys;
using TemplatesPrint.MySqlEntitys;

namespace TemplatesPrint.Tools
{
    public class WsHandlerTool
    {
        public static void OnOpen(string clientInfo)
        {
            //添加到client表中
            //返回本机打印机信息
            using (var db = SQLiteHelper.GetInstance())
            {
                var client = new ClientInfoEntity();
                client.Info = clientInfo;
                client.Status = "0";
                client.IsPrint = "1";
                client.IsReceive = "1";
                client.CreateTime = client.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

                db.Insertable(client).ExecuteCommand();

                var r_dto = new ReturnDto();
                r_dto.MsgId = "init";
                r_dto.MsgType = "init";
                r_dto.Status = 0;
                r_dto.Data = PrinterTool.GetAllPrinter();

                WsServe.SendMessage(clientInfo, JsonConvert.SerializeObject(r_dto, Formatting.None, PublicTool.serializerSettings));
            };
            TaskLogHandle.SaveLog("", "客户端连接", clientInfo);
        }

        public static void OnClose(string clientInfo)
        {
            //从client表中删除
            using (var db = SQLiteHelper.GetInstance())
            {
                var client = db.Queryable<ClientInfoEntity>()
                      .Where(x => x.Info == clientInfo)
                      .Includes(x => x.Tasks)
                      .First();
                if (client != null)
                {
                    if (client.TaskNum > 0)
                    {
                        client.Status = "1";
                        client.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                        db.Updateable(client).ExecuteCommand();
                    }
                    else
                    {
                        db.Deleteable(client).ExecuteCommand();
                    }
                }
            };
            TaskLogHandle.SaveLog("", "客户端断开", clientInfo);
        }

        public static void OnMessage(string clientInfo, string message)
        {
            var r_dto = new ReturnDto();
            r_dto.Data = message;
            r_dto.Status = 0;
            try
            {
                var tp = JsonConvert.DeserializeObject<TaskParamDto>(message);
                r_dto.MsgId = tp.MsgId;
                r_dto.MsgType = tp.MsgType;

                switch (tp.MsgType.ToLower())
                {
                    case "print"://打印
                    case "print_bill"://本地单据打印
                    case "print_label"://本地标签打印
                        ReceivePrint(clientInfo, tp, r_dto);//打印任务
                        break;
                    case "printer":
                        ReceiveQryPrinter(clientInfo, tp, r_dto);//查询打印机
                        break;
                    case "template":
                        ReceiveQryTemplate(clientInfo, tp, r_dto);//查询模板
                        break;
                    case "log":
                        ReceiveQryLog(clientInfo, tp, r_dto);//查询日志
                        break;
                    case "task":
                        ReceiveQryTask(clientInfo, tp, r_dto);//查询任务
                        break;
                    case "code":
                        ReceiveQryCode(clientInfo, tp, r_dto);//查询条码
                        break;
                    case "invalidcode":
                        ReceiveInvalidCode(clientInfo, tp, r_dto);//作废条码
                        break;
                    case "enablecode":
                        ReceiveEnableCode(clientInfo, tp, r_dto);//启用条码
                        break;

                    case "updatecodestatus":
                        UpdateCodestatus(clientInfo, tp, r_dto);//更新条码状态
                        break;

                    default:
                        r_dto.Status = 4;
                        r_dto.IsSuccess = false;
                        r_dto.Message = "消息类型不存在！";
                        break;
                }

                TaskLogHandle.SaveLog(tp.MsgId, "接收任务：" + tp.MsgType + ",来源:" + clientInfo, message);
            }
            catch (Exception ex)
            {
                //接收任务失败，返回信息
                r_dto.Status = 4;
                r_dto.IsSuccess = false;
                r_dto.Message = ex.Message;

                TaskLogHandle.SaveLog("", "接收任务失败,来源[" + clientInfo + "]", message, "false");
            }
            WsServe.SendMessage(clientInfo, JsonConvert.SerializeObject(r_dto, Formatting.None, PublicTool.serializerSettings));
        }
        static void ReceiveInvalidCode(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            for (int i = 0; i < tp.Data.Count(); i++)
            {
                var param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(tp.Data[i]));
                foreach (var v in param.Values)
                {
                    CodeInfoHandle.SaveCode(clientInfo, tp.MsgId, v, "业务指令", "2");
                }
            }
            ReceivePrint(clientInfo, tp, r_dto, "2");
        }

        static void ReceiveEnableCode(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            for (int i = 0; i < tp.Data.Count(); i++)
            {
                var param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(tp.Data[i]));
                foreach (var v in param.Values)
                {
                    CodeInfoHandle.SaveCode(clientInfo, tp.MsgId, v, "业务指令", "1");
                }
            }
            ReceivePrint(clientInfo, tp, r_dto, "2");
        }

        static void UpdateCodestatus(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            for (int i = 0; i < tp.Data.Count(); i++)
            {
                var param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(tp.Data[i]));
                foreach (var p in param)
                {
                    CodeInfoHandle.SaveCode(clientInfo, tp.MsgId, p.Key, "业务指令", p.Value);
                }
            }
            ReceivePrint(clientInfo, tp, r_dto, "2");
        }

        static void ReceivePrint(string clientInfo, TaskParamDto tp, ReturnDto r_dto, string status = "0")
        {
            var task = new TaskInfoEntity();
            task.MsgId = tp.MsgId;
            task.Status = status;
            task.Source = clientInfo;
            task.Type = tp.MsgType;
            task.Printcopies = tp.PrintCopies.ToString();
            task.PrinterInfo = tp.PrinterName;
            task.TemplateInfo = tp.TemplateName;
            task.Data = JsonConvert.SerializeObject(tp.Data, Formatting.None, PublicTool.serializerSettings);
            //var ww = JToken.Parse(task.Data).ToString();
            task.CreateTime = task.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            if (tp.MsgType != "print" && tp.MsgType != "print_bill" && tp.MsgType != "print_label")
            {
                task.UpdateTime = task.StartTime = task.EndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                TaskInfoHandle.SaveTaskHistory(Guid.NewGuid().ToString("N"), task);
            }
            else
            {
                if (string.IsNullOrEmpty(tp.TemplateName))
                {
                    r_dto.Status = 4;
                    r_dto.IsSuccess = false;
                    r_dto.Message = "打印模板不能为空";
                }
                else
                {
                    using (var db = SQLiteHelper.GetInstance())
                    {
                        var t = db.Insertable(task).ExecuteReturnEntity();
                        (new PublicTool()).AddPrintThead(new List<TaskInfoEntity> { t });
                        if (PublicTool.GetTemplatesType.ToLower() != "LocalFile".ToLower())//本地模式
                        {

                            List<dynamic> uploads = new List<dynamic>();
                            var tmp = new
                            {
                                taskId = task.Id.ToString(),
                                source = task.Source,
                                type = task.Type,
                                templateInfo = task.TemplateInfo,
                                printerInfo = task.PrinterInfo,
                                data = task.Data,
                                printCopies = task.Printcopies,
                                startTime = string.IsNullOrEmpty(task.StartTime) ? null : task.StartTime,
                                endTime = string.IsNullOrEmpty(task.StartTime) ? null : task.EndTime,
                                updateTime= task.UpdateTime == null ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : task.UpdateTime,
                                status = task.Status,
                                exInfo = task.ExInfo,
                                msgId = task.MsgId,
                                sourceIp = IpTools.GetMacAddress()
                            };
                            uploads.Add(tmp);
                            var state = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/batch/task-info", JsonConvert.SerializeObject(uploads), out string ret);
                            if (state)
                            {
                                var result = JObject.Parse(ret);
                                if (result["code"] != null && result["code"].ToString() != "0")
                                {
                                    state = false;
                                    ret = "batch/task-info:接口异常" + result["message"].ToString();
                                }
                            }
                            if (!state)
                            {
                                TaskLogHandle.SaveLog("", "上传任务：异常", ret, "false", "上传");
                            }
                        }
                    };
                }
            }
        }

        static void ReceiveQryPrinter(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            var printers = PrinterTool.GetAllPrinter();
            r_dto.Data = printers;
            ReceivePrint(clientInfo, tp, r_dto, "2");
        }
        static void ReceiveQryTemplate(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            try
            {
                var tmp = new
                {
                    page = 1,
                    size = 10000,
                    status = 1
                };
                var ok = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/template/pager", JsonConvert.SerializeObject(tmp), out string ret);
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    if (result["code"] != null && result["code"].ToString() != "0")
                    {
                        ok = false;
                        ret = "template/pager:接口异常" + result["message"].ToString();
                    }
                }
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    var items = JArray.Parse(result["data"]["records"].ToString());
                    List<dynamic> data = new List<dynamic>();
                    foreach (var v in items)
                    {
                        data.Add(new
                        {
                            id = v["bizKey"].ToString(),
                            describe = v["describe"].ToString(),
                            status = v["status"].ToString(),
                            memo = v["memo"].ToString(),
                            createTime = v["createTime"].ToString(),
                            updateTime = v["updateTime"].ToString()
                        }
                        );
                    }
                    r_dto.Data = data;
                    ReceivePrint(clientInfo, tp, r_dto, "2");
                }
                else
                {
                    r_dto.Status = 4;
                    r_dto.IsSuccess = false;
                    r_dto.Message = ret;
                    TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询模板信息", ret, "false");
                }
            }
            catch (Exception ex)
            {
                r_dto.Status = 4;
                r_dto.IsSuccess = false;
                r_dto.Message = ex.Message;
                TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询模板信息", ex.ToString(), "false");
            }
        }

        static void ReceiveQryCode(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {

            try
            {
                var param = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(tp.Data[0]));
                var checkcode = param["code"];
                var ok = PublicTool.HttpGetData($"{ PublicTool.ServerDbIp}/print/v1/open/code-info/{checkcode}", Encoding.UTF8, out string ret);
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    if (result["code"] != null && result["code"].ToString() != "0")
                    {
                        ok = false;
                        ret = $"code-info/{checkcode}:接口异常" + result["message"].ToString();
                    }
                }
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    var items = JArray.Parse(result["data"].ToString());
                    List<dynamic> data = new List<dynamic>();
                    foreach (var v in items)
                    {
                        data.Add(new
                        {
                            barcode = v["barCode"].ToString(),
                            codeType = v["codeType"].ToString(),
                            status = v["status"].ToString(),
                            createTime = v["createTime"].ToString(),
                        }
                        );
                    }
                    r_dto.Data = data;
                    ReceivePrint(clientInfo, tp, r_dto, "2");
                }
                else
                {
                    r_dto.Status = 4;
                    r_dto.IsSuccess = false;
                    r_dto.Message = ret;
                    TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询模板信息", ret, "false");
                }
            }
            catch (Exception ex)
            {
                r_dto.Status = 4;
                r_dto.IsSuccess = false;
                r_dto.Message = ex.Message;
                TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询条码信息", ex.ToString(), "false");
            }
        }


        static void ReceiveQryTask(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            //查询任务
            try
            {
                var tmp = new
                {
                    page = 1,
                    size = 10,
                    msgId = tp.MsgId
                };
                var ok = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/task-info/pager", JsonConvert.SerializeObject(tmp), out string ret);
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    if (result["code"] != null && result["code"].ToString() != "0")
                    {
                        ok = false;
                        ret = "task-info/pager:接口异常" + result["message"].ToString();
                    }
                }
                if (ok)
                {
                    var result = JObject.Parse(ret);
                    var items = JArray.Parse(result["data"]["records"].ToString());
                    List<dynamic> data = new List<dynamic>();
                    if (items.Count>0)
                    {
                        var v = items.OrderByDescending(e=>e["createTime"]).FirstOrDefault();
                        data.Add(new
                        {
                            MagId = tp.MsgId,
                            MegType = v["type"].ToString(),
                            PrintName = v["printerInfo"].ToString(),
                            TemplateName = v["templateInfo"].ToString(),
                            Status = v["status"].ToString(),
                            createTime = v["createTime"].ToString(),
                        }
                       );
                    }
                    tp.Data = new List<object>();
                    tp.Data.Add(tp.MsgId);
                    tp.MsgId = Guid.NewGuid().ToString();
                   
                    r_dto.Data = data;
                    r_dto.MsgId = tp.MsgId;
                    ReceivePrint(clientInfo, tp, r_dto, "2");
                }
                else
                {
                    r_dto.Status = 4;
                    r_dto.IsSuccess = false;
                    r_dto.Message = ret;
                    TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询任务信息", ret, "false");
                }
            }
            catch (Exception ex)
            {
                r_dto.Status = 4;
                r_dto.IsSuccess = false;
                r_dto.Message = ex.Message;
                TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询任务信息", ex.ToString(), "false");
            }
        }

        static void ReceiveQryLog(string clientInfo, TaskParamDto tp, ReturnDto r_dto)
        {
            try
            {
                var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(JsonConvert.SerializeObject(tp.Data[0]));
                var ret = new Dictionary<string, object>();
                ret.Add("data", null);
                ret.Add("total", 0);
                int pageIndex = 1, pageSize = 10, totalCount = 0; ;
                if (dic.ContainsKey("pageIndex"))
                {
                    pageIndex = int.Parse(dic["pageIndex"]);
                }
                if (dic.ContainsKey("pageSize"))
                {
                    pageSize = int.Parse(dic["pageSize"]);
                }

                var tmp = new
                {
                    page = pageIndex,
                    size = pageSize,
                    taskId = dic.ContainsKey("msgId") ? dic["msgId"] : null,
                    code = dic.ContainsKey("code") ? dic["code"] : null,
                    printer = dic.ContainsKey("printer") ? dic["printer"] : null,
                    templateId = dic.ContainsKey("templateName") ? dic["templateName"] : null,
                    startTime = dic.ContainsKey("startTime") ? dic["startTime"] : null,
                    endTime = dic.ContainsKey("endTime") ? dic["endTime"] : null,
                };

                var ok = PublicTool.Post($"{ PublicTool.ServerDbIp}/print/v1/open/task-log/pager", JsonConvert.SerializeObject(tmp), out string str);
                if (ok)
                {
                    var result = JObject.Parse(str);
                    if (result["code"] != null && result["code"].ToString() != "0")
                    {
                        ok = false;
                        str = "task-log/pager:接口异常" + result["message"].ToString();
                    }
                }
                if (ok)
                {
                    List<dynamic> data = new List<dynamic>();
                    var result = JObject.Parse(str);
                    totalCount = int.Parse(result["data"]["total"].ToString());
                    if (totalCount>0)
                    {
                        var items = JArray.Parse(result["data"]["records"].ToString());
                        foreach (var v in items)
                        {
                            data.Add(new
                            {
                                id = v["id"].ToString(),
                                msgId = v["taskId"].ToString(),
                                status = v["status"].ToString(),
                                msg = v["msg"].ToString(),
                                createTime = v["createTime"].ToString(),
                            }
                            );
                        }
                    }
                    ret["total"] = totalCount;
                    ret["data"] = data;
                    ret.Add("pageIndex", pageIndex);
                    ret.Add("pageSize", pageSize);
                    r_dto.Data = ret;
                    ReceivePrint(clientInfo, tp, r_dto, "2");
                }
                else
                {
                    r_dto.Status = 4;
                    r_dto.IsSuccess = false;
                    r_dto.Message = str;
                    TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询模板信息", str, "false");
                }
            }
            catch (Exception ex)
            {
                r_dto.Status = 4;
                r_dto.IsSuccess = false;
                r_dto.Message = ex.Message;
                TaskLogHandle.SaveLog(tp.MsgId, "系统异常：查询日志信息", ex.ToString(), "false");
            }
        }

    }
}
